package ani.trainning.cacobatph;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
import ani.trainning.cacobatph.dac.ACT3_DACprincipale;
import ani.trainning.cacobatph.dac.ACT4_DACcomplementaire;
import ani.trainning.cacobatph.das.Act6_Das;


public class ACT1_authentification extends Activity implements OnClickListener {

	EditText editUser;
	Thread thread;
	EditText editPass;
	Button boutonConnexion;
	String user;
	String pass;
	utilities utile;
	Context context;
	ProgressDialog progressDialog;
	Builder alert;
	LinearLayout layout;
	private SharedPreferences myPrefs;
	private Editor prefsEditor;
	private boolean customTitleSupported;
	public static String CACOBATPH="CACOBATPH";
	public static String FERMER_CACOBATPH = "Voulez vous quitter CACOBATPH";
	
	public static final int REQUEST_CODE = 0661540475;
	public static final int RESULT_CODE = 066154043;


	
	/** Called when the activity is first created. */

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		customTitleSupported=requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.lay_authentification);
		context=this;
		utilities.customTitleBar((Activity) context, getText(R.string.app_name).toString(), "Connexion", customTitleSupported);
		editUser=(EditText) this.findViewById(R.id.editUserName);
		editPass=(EditText) this.findViewById(R.id.EditPass);
		boutonConnexion=(Button) this.findViewById(R.id.boutonConnexion);
		boutonConnexion.setOnClickListener(this);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == REQUEST_CODE) {
			switch (resultCode) {
			case RESULT_CODE:
				setResult(RESULT_CODE);
				finish();
				break;
			}
		}
	}
	
	@Override
	public void onClick(View arg0) {

		try {
			if(editUser.getText().toString()==null ||editUser.getText().toString().equals("")||editPass.getText().toString().equals("")||editPass.getText().toString()==null)
			{
				utilities.alerte(context, "Veuillez saisir le nom d'utilisateur et le Mot de passe", CACOBATPH, R.drawable.alerte_logo);
			}else{
				user=editUser.getText().toString();
				pass=editPass.getText().toString();
				myPrefs = context.getSharedPreferences(ConstantUtil.MYPREFS, ConstantUtil.MODE);
				prefsEditor = myPrefs.edit();

						user="09319046";//16116923
						pass="void2011";
				prefsEditor.putString(ConstantUtil.USER, user);
				prefsEditor.putString(ConstantUtil.PASS, pass);
				Handler handler = new Handler() {
					@Override
					public void handleMessage(Message msg) {
						progressDialog.dismiss();
						switch (msg.what) {
						case ACT3_DACprincipale.RESULTAT_CORRECTE:
							decoderJson(msg.obj.toString());
							break;

						case ACT3_DACprincipale.EXEPTIONS:
							utilities.alerteExeption(context, ConstantUtil.MESSAGE_EXCEPTION, false);
							break;

						case ACT3_DACprincipale.EXEPTION_IO:
							utilities.alerteExeption(context, ConstantUtil.MESSAGE_IOEXCEPTION, false);
							break;
						}
					}
				};
				THR1_authentification classThread = new THR1_authentification(handler, context,user,pass);
				thread = classThread.createThread();
				thread.start();
				showDialog(0);

			}
		} catch (Exception e) {

			Log.e("", ""+e.getMessage());

		}
	//	finish();
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		progressDialog = new ProgressDialog(context);
		progressDialog.setMessage("Chargement en cours");
		progressDialog.setCancelable(false);
		progressDialog.setIndeterminate(true);
		return progressDialog;
	}

	private void decoderJson(String string) {
		try {
			JSONObject jSon=new JSONObject(string);
			int code=jSon.getInt("code");
			switch (code) {
			case ACT3_DACprincipale.RESULTAT_CORRECTE:
				//ok
				getInfos(jSon);
				Intent intent = new Intent(context, ACT2_accueil.class);
				((Activity) context).startActivityForResult(intent, REQUEST_CODE);
				editUser.setText("");
				editPass.setText("");
				break;
			case ACT3_DACprincipale.ECHEC_1:
				utilities.alerte(context, jSon.getString("description"), CACOBATPH, R.drawable.alerte_logo);
				getInfos(jSon);
				Intent intent1 = new Intent(context, ACT2_accueil.class);
				((Activity) context).startActivityForResult(intent1, REQUEST_CODE);
				editUser.setText("");
				editPass.setText("");
				break;
			case ACT3_DACprincipale.ECHEC_2:
				utilities.alerte(context, jSon.getString("description"), CACOBATPH, R.drawable.alerte_logo);
				break;
			case ACT3_DACprincipale.ECHEC_3:
				utilities.alerte(context, jSon.getString("description"), CACOBATPH, R.drawable.alerte_logo);
				break;
			case ACT3_DACprincipale.ECHEC_4:
				utilities.alerte(context, jSon.getString("description"), CACOBATPH, R.drawable.alerte_logo);
				break;


			}

		} catch (JSONException e) {
			Log.e("json exception",""+ e.getMessage());
		}

	}

	private void getInfos(JSONObject jObject) throws JSONException {

		String jsonString =jObject.getString("objet");
		JSONObject jsonObject = new JSONObject(jsonString);


		prefsEditor.putString(ConstantUtil.USER_ID, jsonObject.getString(ConstantUtil.USER_ID));
		prefsEditor.putString(ConstantUtil.MAIL, jsonObject.getString(ConstantUtil.MAIL));
		prefsEditor.putString(ConstantUtil.RAISON_SOCIALE,jsonObject.getString(ConstantUtil.RAISON_SOCIALE));
		prefsEditor.putString(ConstantUtil.AGENE_ID, jsonObject.getString(ConstantUtil.AGENE_ID));
		prefsEditor.putString(ConstantUtil.AGENCE_LIBELLE,jsonObject.getString(ConstantUtil.AGENCE_LIBELLE) );
		prefsEditor.putString(ConstantUtil.ADRESSE, jsonObject.getString(ConstantUtil.ADRESSE));
		prefsEditor.putString(ConstantUtil.WILAYA, jsonObject.getString(ConstantUtil.WILAYA));
		prefsEditor.putString(ConstantUtil.TELEPHONE, jsonObject.getString(ConstantUtil.TELEPHONE));
		prefsEditor.putString(ConstantUtil.NUMERO_COTISANT, jsonObject.getString(ConstantUtil.NUMERO_COTISANT));
		prefsEditor.putBoolean(ConstantUtil.SOUS_CONTENTIEUX, jsonObject.getBoolean(ConstantUtil.SOUS_CONTENTIEUX));

		prefsEditor.commit();


	}

	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
	
	
	    if(keyCode == KeyEvent.KEYCODE_BACK)
	    {  
	    	utilities.alerteDeconnexion(context, FERMER_CACOBATPH );
	    }
	    else if(keyCode == KeyEvent.KEYCODE_HOME)
	    {	    	
	    	utilities.alerteDeconnexion(context, FERMER_CACOBATPH );
	    }
	    return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onAttachedToWindow() {
	    this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
	    super.onAttachedToWindow();
	}


}